import { Graph, Node, Cell } from '@antv/x6';

export function getConfig(
  target: Graph,
  configs: any,
  assets: any,
  onNodeCreate: (node: Node) => void,
): any {
  const { title, search, options } = configs;
  return {
    title,
    target,
    animation: false,
    validateNode: (node: Node) => {
      onNodeCreate && onNodeCreate(node);
      return false;
    },
    getDragNode: (node: any) => {
      const { value, moduleType, moduleImage } = node.data;
      const image =
        assets[moduleImage] ||
        assets[`${moduleType ? moduleType : value}Module`] ||
        moduleImage;
      return target.createNode({
        shape: 'lane-node',
        label: node.label,
        data: node.data,
        attrs: {
          body: {
            fill: '#ccc',
          },
          itemTag: {
            xlinkHref: image,
          },
          backgorund: {
            xlinkHref: assets['innerSystem'],
          },
        },
      });
    },
    search: (cell: Cell, keyword: string) => {
      if (keyword) {
        return (
          cell.shape === 'moduleNode' &&
          `${cell.attr('text/text')}`
            .toLowerCase()
            .includes(`${keyword}`.toLowerCase())
        );
      }
      return true;
    },
    placeholder: search?.placeholder || '请输入组件名称',
    stencilGraphWidth: 200,
    collapsable: false,
    groups: options.map(({ label, value, children }: any) => ({
      title: label,
      name: value,
      collapsable: false,
      graphPadding: 0,
      graphHeight: (Array.isArray(children) ? children.length * 32 : 0) + 10,
      layoutOptions: {
        columns: 1,
        columnWidth: 190,
        rowHeight: 32,
        dx: 5,
        dy: 5,
      },
    })),
  };
}

export function appendOptions(
  graph: Graph,
  stencil: any,
  options: any[],
  assets: any,
) {
  const moduleProps: any = {};
  const modules: any = {};
  options.forEach((group) => {
    const { value: groupName, children } = group;
    if (!Array.isArray(children)) return;
    const items = children.map((item) => {
      const { label, value, icon, moduleType, moduleProp } = item;
      moduleProps[moduleType || value] = moduleProp;
      modules[moduleType || value] = item;
      delete item.moduleProp;
      const image = assets[`${icon}Icon`] || icon;
      item.moduleType = moduleType || value;
      const node = graph.createNode({
        shape: 'moduleNode',
        label,
        data: item,
      });
      node.attr('icon/xlinkHref', image);
      return node;
    });
    stencil.load(items, groupName);
  });
  (window as any)._moduleProps = moduleProps;
  (window as any)._modules = modules;
}
